package com.solution.admin.promotion.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.solution.admin.auth.constants.AuthConstants.IS_DELETE;
import com.solution.admin.coupon.entity.CouponEntity;
import com.solution.admin.coupon.service.CouponService;
import com.solution.admin.home.constants.SequenceConstants.SequenceLength;
import com.solution.admin.home.constants.SequenceConstants.SequenceNameConsts;
import com.solution.admin.home.constants.SequenceConstants.SequenceRedisKey;
import com.solution.admin.home.service.SequenceService;
import com.solution.admin.promotion.entity.PromotionEntity;
import com.solution.admin.promotion.entity.PromotionProductEntity;
import com.solution.admin.promotion.entity.PromotionRuleDiscountEntity;
import com.solution.admin.promotion.entity.PromotionRuleGiftEntity;
import com.solution.admin.promotion.entity.PromotionRuleReduceEntity;
import com.solution.admin.promotion.entity.PromotionTargetEntity;
import com.solution.admin.promotion.service.PromotionProductService;
import com.solution.admin.promotion.service.PromotionRuleDiscountService;
import com.solution.admin.promotion.service.PromotionRuleGiftService;
import com.solution.admin.promotion.service.PromotionRuleReduceService;
import com.solution.admin.promotion.service.PromotionService;
import com.solution.admin.promotion.service.PromotionTargetService;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.admin.settings.service.KeyMapService;
import com.solution.common.constants.PublicStatus.STATUS;
import com.solution.common.constants.PublicStatus.SysCode;
import com.solution.common.constants.PublicStatus.SysSymbol;
import com.solution.common.controller.BaseController;
import com.solution.common.entity.BaseReturn;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.DateUtils;
import com.solution.common.utils.string.StringUtil;

/**
 * 活动信息web控制层
 * 
 * @author xu_cc
 * @date 2017-09-27 23:24:51
 */
@RequestMapping("/promotion")
@Controller
public class PromotionController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(PromotionController.class);

	/** 活动类型-满减 */
	static final Integer RULE_REDUCE = 1;
	/** 活动类型-满赠 */
	static final Integer RULE_GIFT = 2;
	/** 活动类型-折扣 */
	static final Integer RULE_DISCOUNT = 3;

	/** 操作类型-修改状态 */
	static final int DO_MODIFY_STATUS = 1;
	/** 操作类型-编辑 */
	static final int DO_MODIFY = 2;
	/** 操作类型-删除 */
	static final int DO_DELETE = 3;

	@Autowired
	PromotionService promotionService;

	@Autowired
	PromotionTargetService promotionTargetService;
	@Autowired
	PromotionProductService promotionProductService;
	@Autowired
	PromotionRuleReduceService ruleReduceService;
	@Autowired
	PromotionRuleGiftService ruleGiftService;
	@Autowired
	PromotionRuleDiscountService ruleDiscountService;

	@Autowired
	KeyMapService keyMapService;

	@Autowired
	SequenceService sequenceService;

	@Autowired
	CouponService couponService;

	/**
	 * 根据活动时间获取满赠优惠券列表
	 * 
	 * @param request
	 * @param promotionDate
	 * @return List<CouponEntity>
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年11月21日 下午4:45:52
	 */
	@RequestMapping("/getCouponList")
	@ResponseBody
	public List<CouponEntity> getCouponList(HttpServletRequest request, String promotionDate) {
		try {
			if (StringUtil.isEmpty(promotionDate)) {
				return null;
			}
			// 时间
			if (promotionDate.indexOf(" - ") > 0) {
				String[] promotionDateArr = promotionDate.split(" - ");
				Date beginTime = DateUtils.parseDate(promotionDateArr[0]);
				Date endTime = DateUtils.parseDate(promotionDateArr[1]);
				List<CouponEntity> list = couponService.listByPromotionCombo(beginTime, endTime);
				return list;
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 跳转活动信息查询页面
	 * 
	 * @param Promotion
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author xu_cc
	 * @date 2017-09-27 23:24:51
	 */
	@RequestMapping("/toListPromotionPage")
	public String toListPromotionPage(PromotionEntity promotion, HttpServletRequest request, Model model) {
		model.addAttribute("systemTime", System.currentTimeMillis());
		return "promotion/promotion_list";
	}

	/**
	 * 获取服务器时间
	 * 
	 * @Title: getSystemTime
	 * @Description:(描述)
	 * @return Long
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年10月11日 下午7:51:33
	 */
	@RequestMapping("/systemTime")
	public Long getSystemTime() {
		return System.currentTimeMillis();
	}

	/**
	 * 分页查询活动信息列表
	 * 
	 * @param promotion
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author xu_cc
	 * @date 2017-09-27 23:24:51
	 */
	@RequestMapping("/listPromotionPage")
	@ResponseBody
	public JSONGrid listPromotionPage(HttpServletRequest request, PromotionEntity promotion, String promotionDate) {
		int pageNum = Integer.parseInt(request.getParameter("page").toString());
		int numPerPage = Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);

		Map<String, Object> paramMap = new HashMap<String, Object>();
		// 时间
		if (StringUtil.isNotNull(promotionDate) && promotionDate.indexOf(" - ") > 0) {
			String[] promotionDateArr = promotionDate.split(" - ");
			Date beginTime = DateUtils.parseDate(promotionDateArr[0]);
			Date endTime = DateUtils.parseDate(promotionDateArr[1]);
			paramMap.put("beginTime", beginTime);
			paramMap.put("endTime", endTime);
		}
		paramMap.put("promotionCode", promotion.getPromotionCode());
		paramMap.put("promotionType", promotion.getPromotionType());
		paramMap.put("promotionName", promotion.getPromotionName());
		paramMap.put("status", promotion.getStatus());
		try {
			PageBean pageBean = promotionService.listPromotionPage(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(), pageBean.getTotalCount());
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return new JSONGrid();
	}

	/**
	 * 根据活动ID、商品类型、规则ID获取活动商品（条件商品、满赠商品）
	 * 
	 * @param request
	 * @param promotionId
	 * @param productType
	 * @param promotionRuleId
	 * @return JSONGrid
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年10月10日 下午8:36:26
	 */
	@RequestMapping("/productList")
	@ResponseBody
	public JSONGrid productList(HttpServletRequest request, Long promotionId, String productType, Long promotionRuleId) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			// 如果活动ID或者商品类型为空，返回空集合
			if (null == promotionId || StringUtil.isEmpty(productType)) {
				return new JSONGrid();
			}
			paramMap.put("promotionId", promotionId);
			paramMap.put("productType", productType);
			paramMap.put("promotionRuleId", promotionRuleId);
			List<PromotionProductEntity> list = promotionProductService.listPromotionProduct(paramMap);
			return new JSONGrid(list, list.size());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new JSONGrid();
	}

	/**
	 * 跳转新增页面
	 * 
	 * @return string 跳转页面路径
	 * @author xu_cc
	 * @date 2017-09-27 23:24:51
	 */
	@RequestMapping("/toAddPromotion")
	public String toAddPromotion(HttpServletRequest request, Model model) {
		// 初始化对象类型
		model.addAttribute("targetType", 1);
		// 序列号
		String seqCode = sequenceService.getSequenceNumber(SequenceRedisKey.REDIS_SEQ_PROMOTION, SequenceLength.LENGTH_PROMOTION);
		// 活动编码
		String promotionCode = SequenceNameConsts.SEQ_PROMOTION.concat(seqCode);
		PromotionEntity promotion = new PromotionEntity();
		promotion.setPromotionCode(promotionCode);
		model.addAttribute("promotion", promotion);
		List<KeyMapEntity> typeList = keyMapService.listKeyMap("promotionType");
		model.addAttribute("promotionTypeList", typeList);
		return "promotion/promotion_form";
	}

	/**
	 * 跳转活动详情页面
	 * 
	 * @Title: toPromotionDetailPage
	 * @Description:(描述)
	 * @param request
	 * @param model
	 * @param id
	 * @return String
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年10月11日 下午8:24:28
	 */
	@RequestMapping("/toPromotionDetailPage")
	public String toPromotionDetailPage(HttpServletRequest request, Model model, Long id) {
		try {
			List<KeyMapEntity> typeList = keyMapService.listKeyMap("promotionType");
			model.addAttribute("promotionTypeList", typeList);
			PromotionEntity promotion = promotionService.getPromotionById(id);
			model.addAttribute("promotion", promotion);
			// 活动类型
			model.addAttribute("promotionType", promotion.getPromotionType());
			// 获取活动对象
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("promotionId", id);
			List<PromotionTargetEntity> targetList = promotionTargetService.listPromotionTarget(map);
			model.addAttribute("targetList", targetList);
			// // 活动对象类型
			// model.addAttribute("targetType",
			// targetList.get(0).getTargetType());
			// 拼接活动起止时间
			String beginDate = DateUtils.formatDateTime(promotion.getBeginTime());
			String endDate = DateUtils.formatDateTime(promotion.getEndTime());
			model.addAttribute("promotionDate", beginDate + " - " + endDate);
			// 根据活动类型，获取活动规则
			if (RULE_REDUCE.equals(promotion.getPromotionType())) {
				// 满减
				List<PromotionRuleReduceEntity> ruleReduceList = ruleReduceService.listPromotionRuleReduce(id);
				model.addAttribute("ruleReduceList", ruleReduceList);
				// 上不封顶
				model.addAttribute("isLimit", ruleReduceList.get(0).getIsLimit());
			} else if (RULE_GIFT.equals(promotion.getPromotionType())) {
				// 满赠
				List<PromotionRuleGiftEntity> ruleGiftList = ruleGiftService.listPromotionRuleGift(id);
				model.addAttribute("ruleGiftList", ruleGiftList);
			} else if (RULE_DISCOUNT.equals(promotion.getPromotionType())) {
				// 折扣
				List<PromotionRuleDiscountEntity> ruleDiscountList = ruleDiscountService.listPromotionRuleDiscount(id);
				model.addAttribute("ruleDiscountList", ruleDiscountList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "promotion/promotion_detail";
	}

	/**
	 * 跳转编辑页面
	 * 
	 * @return string 跳转页面路径
	 * @author xu_cc
	 * @date 2017-09-27 23:24:51
	 */
	@RequestMapping("/toUpdatePromotion")
	public String toUpdatePromotion(HttpServletRequest request, Model model, Long id) {
		// 编辑操作
		try {
			List<KeyMapEntity> typeList = keyMapService.listKeyMap("promotionType");
			model.addAttribute("promotionTypeList", typeList);
			PromotionEntity promotion = promotionService.getPromotionById(id);
			model.addAttribute("promotion", promotion);
			// 活动类型
			model.addAttribute("promotionType", promotion.getPromotionType());
			// 获取活动对象
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("promotionId", id);
			map.put("isDelete", IS_DELETE.NOT_DELETE.getId());
			map.put("status", STATUS.ENABLED.getId());
			List<PromotionTargetEntity> targetList = promotionTargetService.listPromotionTarget(map);
			model.addAttribute("targetList", targetList);
			// // 活动对象类型
			// model.addAttribute("targetType",
			// targetList.get(0).getTargetType());
			// 拼接活动起止时间
			String beginDate = DateUtils.formatDateTime(promotion.getBeginTime());
			String endDate = DateUtils.formatDateTime(promotion.getEndTime());
			model.addAttribute("promotionDate", beginDate + " - " + endDate);
			// 根据活动类型，获取活动规则
			if (RULE_REDUCE.equals(promotion.getPromotionType())) {
				// 满减
				List<PromotionRuleReduceEntity> ruleReduceList = ruleReduceService.listPromotionRuleReduce(id);
				model.addAttribute("ruleReduceList", ruleReduceList);
				// 上不封顶
				model.addAttribute("isLimit", ruleReduceList.get(0).getIsLimit());
			} else if (RULE_GIFT.equals(promotion.getPromotionType())) {
				// 满赠
				List<PromotionRuleGiftEntity> ruleGiftList = ruleGiftService.listPromotionRuleGift(id);
				model.addAttribute("ruleGiftList", ruleGiftList);
			} else if (RULE_DISCOUNT.equals(promotion.getPromotionType())) {
				// 折扣
				List<PromotionRuleDiscountEntity> ruleDiscountList = ruleDiscountService.listPromotionRuleDiscount(id);
				model.addAttribute("ruleDiscountList", ruleDiscountList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "promotion/promotion_form";
	}

	/**
	 * 新增或保存活动信息
	 * 
	 * @param request
	 *            请求对象
	 * @param promotionEntity
	 *            活动信息实体
	 * @return
	 * @author xu_cc
	 * @date 2017-09-27 23:24:51
	 */
	@RequestMapping("/savePromotion")
	@ResponseBody
	public BaseReturn savePromotion(HttpServletRequest request, PromotionEntity promotionEntity, String promotionDate) {
		BaseReturn result = new BaseReturn();
		try {
			// 活动日期
			String[] promotionDateArr = promotionDate.split(" - ");
			Date startDate = DateUtils.parseDate(promotionDateArr[0]);
			Date endDate = DateUtils.parseDate(promotionDateArr[1]);
			promotionEntity.setBeginTime(startDate);
			promotionEntity.setEndTime(endDate);

			promotionEntity.setIsDelete(IS_DELETE.NOT_DELETE.getId());
			promotionEntity.setStatus(STATUS.ENABLED.getId());
			promotionEntity.setCreater(getUserName());
			promotionEntity.setModifier(getUserName());

			// 是否选择商品
			if (StringUtil.isEmpty(promotionEntity.getProductStr())) {
				result.setCode(SysCode.FAILED);
				result.setMsg("请选择活动商品！");
				return result;
			}
			// 是否选择对象
			if (StringUtil.isEmpty(promotionEntity.getTargetStr())) {
				result.setCode(SysCode.FAILED);
				result.setMsg("请选择活动对象！");
				return result;
			}
			// 是否输入规则
			if (StringUtil.isEmpty(promotionEntity.getRuleJsonArr())) {
				result.setCode(SysCode.FAILED);
				result.setMsg("请编辑正确的活动规则！");
				return result;
			}
			/** 增加活动商品时段校验（同一时间段内同一商品不可参加多个活动） */
			List<Map<String, Object>> checkMapList = new ArrayList<Map<String, Object>>();
			// 插入活动商品
			String[] proIdArr = promotionEntity.getProductStr().split(SysSymbol.COMMA);
			if (null != proIdArr && proIdArr.length > 0) {
				Map<String, Object> checkMap = null;
				for (String productCode : proIdArr) {
					if (StringUtil.isEmpty(productCode)) {
						continue;
					}
					checkMap = new HashMap<String, Object>();
					checkMap.put("productCode", productCode);
					checkMap.put("beginTime", promotionDateArr[0]);
					checkMap.put("endTime", promotionDateArr[1]);
					checkMapList.add(checkMap);
				}
				// 同时间段，冲突商品集合
				List<PromotionEntity> existsPromotionProductList = promotionService.getPromotionProductByTime(checkMapList);
				if (null != existsPromotionProductList && existsPromotionProductList.size() > 0) {
					// 集合不为空，说明存在有冲突时间段的商品
					StringBuffer error = new StringBuffer("活动商品的时间段设置与已有活动冲突！<br/>");
					boolean isError = false; // 默认没错
					for (PromotionEntity existsPromotion : existsPromotionProductList) {
						// 排除本身
						if (existsPromotion.getId().equals(promotionEntity.getId())) {
							continue;
						} else {
							isError = true;
							error.append("冲突活动：").append(existsPromotion.getPromotionName()).append("(").append(existsPromotion.getPromotionCode())
							        .append(")<br/>").append("冲突商品：").append(existsPromotion.getProductName()).append("(")
							        .append(existsPromotion.getProductCode()).append(")<br/>").append("冲突时段：")
							        .append(DateUtils.formatDateTime(existsPromotion.getBeginTime())).append(" 至 ")
							        .append(DateUtils.formatDateTime(existsPromotion.getEndTime())).append("<br/>");
						}
					}
					if (isError) {
						result.setCode(SysCode.FAILED);
						result.setMsg(error.toString());
						return result;
					} else {
						// doing nothing
						// 说明获取的冲突记录是本身
					}
				} else {
					// doing nothing
					// 说明不存在冲突时段的商品
				}
			} else {
				result.setCode(SysCode.FAILED);
				result.setMsg("解析活动商品异常！");
				return result;
			}
			// 开始保存活动信息
			int rows = 0;
			if (null == promotionEntity.getId()) {
				rows = promotionService.savePromotion(promotionEntity);
			} else {
				if (checkTimeStatus(promotionEntity.getId(), DO_MODIFY)) {
					rows = promotionService.updatePromotion(promotionEntity);
				} else {
					result.setCode(SysCode.FAILED);
					result.setMsg("您只能修改未开始的活动，请刷新重试！");
					return result;
				}
			}
			if (rows > 0) {
				result.setCode(SysCode.SUCCESS);
				result.setMsg("活动信息保存成功！");
			} else {
				result.setCode(SysCode.FAILED);
				result.setMsg("活动信息保存失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.ERROR);
			result.setMsg("保存活动信息异常。");
		}
		return result;
	}

	/**
	 * 修改活动状态
	 * 
	 * @Title: updateStatus
	 * @Description:(描述)
	 * @param request
	 * @param id
	 * @param status
	 * @return BaseReturn
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年10月11日 下午8:23:02
	 */
	@RequestMapping("/updateStatus")
	@ResponseBody
	public BaseReturn updateStatus(HttpServletRequest request, Long id, String status) {
		BaseReturn result = new BaseReturn();
		try {
			if (checkTimeStatus(id, DO_MODIFY_STATUS)) {
				PromotionEntity promotionEntity = new PromotionEntity();
				promotionEntity.setId(id);
				promotionEntity.setStatus(Integer.parseInt(status));
				promotionEntity.setModifier(getUserName());
				int rows = promotionService.updatePromotionStatus(promotionEntity);
				if (rows > 0) {
					result.setCode(SysCode.SUCCESS);
					result.setMsg("活动状态修改成功！");
				} else {
					result.setCode(SysCode.FAILED);
					result.setMsg("活动状态修改失败！");
				}
			} else {
				result.setCode(SysCode.FAILED);
				result.setMsg("活动状态不允许修改！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.ERROR);
			result.setMsg("活动状态更新异常！");
		}
		return result;
	}

	/**
	 * 比较系统时间，判断活动可否修改
	 * 
	 * @Title: checkTimeStatus
	 * @Description:(描述)
	 * @param promotionId
	 * @param handleType
	 * @return boolean
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年10月12日 上午11:20:23
	 */
	private boolean checkTimeStatus(Long promotionId, int handleType) {
		try {
			Date currentDate = new Date();
			PromotionEntity promotion = promotionService.getPromotionById(promotionId);
			// 未开始状态下，可以进行所有操作,开始时间晚于当前系统时间
			if (promotion.getBeginTime().after(currentDate)) {
				return true;
			} else {
				// 进行中，或者已结束，使其只能修改启用停用状态
				if (DO_MODIFY_STATUS == handleType) {
					return true;
				} else {
					return false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 删除活动
	 * 
	 * @Title: doDelPromotion
	 * @Description:(描述)
	 * @param request
	 * @param id
	 * @return BaseReturn
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年10月11日 下午8:12:34
	 */
	@RequestMapping("/doDelPromotion")
	@ResponseBody
	public BaseReturn doDelPromotion(HttpServletRequest request, Long id) {
		BaseReturn result = new BaseReturn();
		try {
			if (checkTimeStatus(id, DO_DELETE)) {
				int rows = promotionService.deletePromotionById(id);
				if (rows > 0) {
					result.setCode(SysCode.SUCCESS);
					result.setMsg("活动删除成功！");
				} else {
					result.setCode(SysCode.FAILED);
					result.setMsg("活动删除失败！");
				}
			} else {
				result.setCode(SysCode.FAILED);
				result.setMsg("仅允许删除未开始的活动，请刷新重试！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.ERROR);
			result.setMsg("活动删除异常！");
		}
		return result;
	}
}
